from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc, asc, func

from database.connection import get_db
from database.models import ScoreDimensions, DimensionScoreRules
from models.score_dimensions import (
    ScoreDimensionCreate, ScoreDimensionUpdate, ScoreDimensionResponse, ScoreDimensionListResponse,
    DimensionQuery, DimensionWeightUpdate, DimensionNameEnum, ApiResponseWithData, ApiResponseNoData
)
from models.dimension_score_rules import (
    DimensionScoreRuleCreate, DimensionScoreRuleUpdate, DimensionScoreRuleResponse,
    DimensionScoreRuleListResponse, RuleQuery, BatchCreateRulesRequest
)
from utils.auth import get_current_user

router = APIRouter(prefix="/score-dimensions", tags=["评分维度管理"])


# ==================== 评分维度管理 ====================

@router.get("/get", summary="获取评分维度列表")
async def get_score_dimensions(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    dimension_name: Optional[str] = Query(None, description="按维度名称筛选"),
    db: Session = Depends(get_db)
):
    """
    获取评分维度列表
    支持分页、关键词搜索和维度名称筛选
    """
    try:
        # 构建查询条件
        query = db.query(ScoreDimensions)
        
        # 关键词搜索
        if keyword:
            query = query.filter(
                or_(
                    ScoreDimensions.dimension_name.contains(keyword),
                    ScoreDimensions.dimension_desc.contains(keyword)
                )
            )
        
        # 按维度名称筛选
        if dimension_name:
            query = query.filter(ScoreDimensions.dimension_name == dimension_name)
        
        # 获取总数
        total = query.count()
        
        # 分页查询，按权重降序排列
        dimensions = query.order_by(ScoreDimensions.dimension_weight.desc()).offset((page - 1) * size).limit(size).all()
        
        # 转换维度数据格式，将时间格式转换为标准格式（去掉T）
        dimensions_data = [
            {
                "id": dim.id,
                "dimension_name": dim.dimension_name,
                "dimension_weight": dim.dimension_weight,
                "dimension_desc": dim.dimension_desc,
                "create_time": dim.create_time.strftime("%Y-%m-%d %H:%M:%S") if dim.create_time else None
            } for dim in dimensions
        ]
        
        return {
            "code": 200,
            "msg": "获取评分维度列表成功",
            "data": {
                "total": total,
                "items": dimensions_data
            }
        }
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取评分维度列表失败: {str(e)}"
        }


@router.post("/add", summary="创建评分维度")
async def create_score_dimension(
    dimension_data: ScoreDimensionCreate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    创建新的评分维度
    需要管理员权限
    """
    try:
        # 检查管理员权限
        if current_user.get("role") != "admin":
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="权限不足，需要管理员权限"
            )
        
        # 检查维度名称是否已存在
        existing_dimension = db.query(ScoreDimensions).filter(
            ScoreDimensions.dimension_name == dimension_data.dimension_name
        ).first()
        
        if existing_dimension:
            return {
                "code": 400,
                "msg": f"维度名称 '{dimension_data.dimension_name}' 已存在"
            }
        
        # 创建新维度
        new_dimension = ScoreDimensions(
            dimension_name=dimension_data.dimension_name,
            dimension_weight=dimension_data.dimension_weight,
            dimension_desc=dimension_data.dimension_desc
        )
        
        db.add(new_dimension)
        db.commit()
        db.refresh(new_dimension)
        
        return {
            "code": 200,
            "msg": "创建评分维度成功",
            "data": new_dimension
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"创建评分维度失败: {str(e)}"
        }


@router.get("/{dimension_id}", summary="获取评分维度详情")
async def get_score_dimension_detail(
    dimension_id: int,
    db: Session = Depends(get_db)
):
    """
    根据维度ID获取评分维度详情
    """
    try:
        dimension = db.query(ScoreDimensions).filter(ScoreDimensions.id == dimension_id).first()
        
        if not dimension:
            return {
                "code": 404,
                "msg": "评分维度不存在"
            }
        
        return {
            "code": 200,
            "msg": "获取评分维度详情成功",
            "data": dimension
        }
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取评分维度详情失败: {str(e)}"
        }


@router.put("/{dimension_id}", summary="更新评分维度")
async def update_score_dimension(
    dimension_id: int,
    dimension_data: ScoreDimensionUpdate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    更新评分维度信息
    需要管理员权限
    """
    try:
        # 查找维度
        dimension = db.query(ScoreDimensions).filter(ScoreDimensions.id == dimension_id).first()
        
        if not dimension:
            return {
                "code": 404,
                "msg": "评分维度不存在"
            }
        
        # 检查维度名称唯一性（如果要更新名称）
        if dimension_data.dimension_name and dimension_data.dimension_name != dimension.dimension_name:
            existing_dimension = db.query(ScoreDimensions).filter(
                and_(
                    ScoreDimensions.dimension_name == dimension_data.dimension_name,
                    ScoreDimensions.id != dimension_id
                )
            ).first()
            
            if existing_dimension:
                return {
                    "code": 400,
                    "msg": f"维度名称 '{dimension_data.dimension_name}' 已存在"
                }
        
        # 更新字段
        update_data = dimension_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(dimension, field, value)
        
        db.commit()
        db.refresh(dimension)
        
        return {
            "code": 200,
            "msg": "更新评分维度成功",
            "data": dimension
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"更新评分维度失败: {str(e)}"
        }


@router.delete("/{dimension_id}", summary="删除评分维度")
async def delete_score_dimension(
    dimension_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    删除评分维度
    需要管理员权限
    """
    try:
        # 查找维度
        dimension = db.query(ScoreDimensions).filter(ScoreDimensions.id == dimension_id).first()
        
        if not dimension:
            return {
                "code": 404,
                "msg": "评分维度不存在"
            }
        
        # 删除维度
        db.delete(dimension)
        db.commit()
        
        return {
            "code": 200,
            "msg": "删除评分维度成功"
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"删除评分维度失败: {str(e)}"
        }


@router.post("/initialize-default", summary="初始化默认维度配置")
async def initialize_default_dimensions(
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    初始化默认的5个评分维度配置
    按照文档规定的权重和描述
    需要管理员权限
    """
    try:
        # 检查是否已有配置
        existing_count = db.query(ScoreDimensions).count()
        if existing_count > 0:
            return {
                "code": 400,
                "msg": f"已存在{existing_count}个维度配置，无需重复初始化"
            }
        
        # 默认维度配置
        default_dimensions = [
            {
                "dimension_name": "作品概念",
                "dimension_weight": 30,
                "dimension_desc": "作品概念是创作的灵魂，评估核心为主题清晰度、叙事逻辑、创意独特性和情感表达力。考察作品是否有明确的主题思想，故事结构是否完整合理，创意是否新颖有趣，能否引发观众共鸣。"
            },
            {
                "dimension_name": "画面美术",
                "dimension_weight": 25,
                "dimension_desc": "画面美术体现作品的视觉品质，评估角色设计、场景构建、色彩搭配、构图美感等。考察画面风格是否统一，美术水准是否精良，视觉效果是否吸引人，整体美学价值如何。"
            },
            {
                "dimension_name": "动画表演",
                "dimension_weight": 20,
                "dimension_desc": "动画表演展现角色的生命力，评估动作流畅度、表演自然度、节奏把控、镜头运用等。考察角色动作是否生动自然，表演是否富有感染力，镜头语言是否恰当，整体节奏是否合理。"
            },
            {
                "dimension_name": "视听语言",
                "dimension_weight": 15,
                "dimension_desc": "视听语言营造作品氛围，评估音效配乐、声音设计、音画同步、听觉体验等。考察音效是否恰当，配乐是否契合主题，声音层次是否丰富，整体听觉效果是否出色。"
            },
            {
                "dimension_name": "创新性",
                "dimension_weight": 10,
                "dimension_desc": "创新性体现作品的突破精神，评估技术创新、表现手法、创意思维、前瞻性等。考察是否运用新技术新手法，表现形式是否有所突破，创意思路是否独特，是否具有启发意义。"
            }
        ]
        
        # 批量创建维度
        created_dimensions = []
        for dim_config in default_dimensions:
            new_dimension = ScoreDimensions(**dim_config)
            db.add(new_dimension)
            created_dimensions.append(new_dimension)
        
        db.commit()
        
        # 刷新所有创建的维度
        for dimension in created_dimensions:
            db.refresh(dimension)
        
        return {
            "code": 200,
            "msg": "初始化默认维度配置成功",
            "data": {
                "created_count": len(created_dimensions),
                "dimensions": created_dimensions
            }
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"初始化默认维度配置失败: {str(e)}"
        }

    @staticmethod
    def validate_dimension_name(v):
        """
        验证维度名称
        确保维度名称不为空且长度合适
        """
        if not v or not v.strip():
            raise ValueError('维度名称不能为空')
        if len(v.strip()) > 50:
            raise ValueError('维度名称长度不能超过50个字符')
        return v.strip()


# =================================
# dimension_score_rules 维度评分规则
# =================================


@router.post("/{dimension_id}/rules", summary="为维度创建评分规则")
async def create_dimension_score_rule(
    dimension_id: int,
    rule: DimensionScoreRuleCreate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    为指定维度创建评分规则
    
    Args:
        dimension_id: 维度ID
        rule: 规则创建数据
        db: 数据库会话
        current_user: 当前用户
    
    Returns:
        统一格式的API响应，包含创建的规则信息
    """
    try:
        # 检查维度是否存在
        dimension = db.query(ScoreDimensions).filter(ScoreDimensions.id == dimension_id).first()
        if not dimension:
            return {
                "code": 404,
                "msg": f"维度ID {dimension_id} 不存在"
            }
        
        # 强制设置维度ID
        rule.dimension_id = dimension_id
        
        # 检查同一维度下是否已存在相同等级的规则
        existing_rule = db.query(DimensionScoreRules).filter(
            and_(
                DimensionScoreRules.dimension_id == dimension_id,
                DimensionScoreRules.score_level == rule.score_level
            )
        ).first()
        
        if existing_rule:
            return {
                "code": 400,
                "msg": f"维度 '{dimension.dimension_name}' 的 {rule.score_level} 分等级规则已存在"
            }
        
        # 创建新规则
        db_rule = DimensionScoreRules(**rule.dict())
        db.add(db_rule)
        db.commit()
        db.refresh(db_rule)
        
        return {
            "code": 200,
            "msg": "创建评分规则成功",
            "data": {
                "id": db_rule.id,
                "dimension_id": db_rule.dimension_id,
                "score_level": db_rule.score_level,
                "level_desc": db_rule.level_desc,
                "judge_criteria": db_rule.judge_criteria,
                "create_time": db_rule.create_time.strftime("%Y-%m-%d %H:%M:%S") if db_rule.create_time else None
            }
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"创建评分规则失败: {str(e)}"
        }


@router.get("/{dimension_id}/rules", summary="获取维度的所有评分规则")
async def get_dimension_rules(
    dimension_id: int,
    db: Session = Depends(get_db)
):
    """
    获取指定维度的所有评分规则
    
    Args:
        dimension_id: 维度ID
        db: 数据库会话
    
    Returns:
        统一格式的API响应，包含该维度的所有规则列表
    """
    try:
        # 检查维度是否存在
        dimension = db.query(ScoreDimensions).filter(ScoreDimensions.id == dimension_id).first()
        if not dimension:
            return {
                "code": 404,
                "msg": f"维度ID {dimension_id} 不存在",
            }
        
        rules = db.query(DimensionScoreRules).filter(
            DimensionScoreRules.dimension_id == dimension_id
        ).order_by(DimensionScoreRules.score_level.asc()).all()
        
        # 转换为字典格式
        rules_data = [
            {
                "id": rule.id,
                "dimension_id": rule.dimension_id,
                "score_level": rule.score_level,
                "level_desc": rule.level_desc,
                "judge_criteria": rule.judge_criteria,
                "create_time": rule.create_time.strftime("%Y-%m-%d %H:%M:%S") if rule.create_time else None
            } for rule in rules
        ]
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": {
                "dimension_info": {
                    "id": dimension.id,
                    "dimension_name": dimension.dimension_name,
                    "description": dimension.dimension_desc,
                    "weight": float(dimension.dimension_weight),
                    "create_time": dimension.create_time.strftime("%Y-%m-%d %H:%M:%S") if dimension.create_time else None
                },
                "rules": rules_data,
                "total": len(rules_data)
            }
        }
        
    except Exception as e:
        return {
            "code": 500,
            "msg": f"查询失败: {str(e)}",
        }





@router.get("/rules/all", summary="查询所有评分规则")
async def get_all_dimension_score_rules(
    page: int = Query(1, ge=1, description="页码", alias="pageNum"),
    size: int = Query(10, ge=1, le=100, description="每页数量", alias="pageSize"),
    keyword: Optional[str] = Query(None, description="搜索关键词，可搜索维度名称、描述、规则描述、评判标准等"),
    db: Session = Depends(get_db)
):
    """
    查询所有评分规则（支持分页和关键词搜索）
    
    Args:
        page: 页码，从1开始
        size: 每页数量，最大100
        keyword: 搜索关键词，可搜索维度名称、描述、规则描述、评判标准等
        db: 数据库会话
    
    Returns:
        统一格式的API响应，包含维度信息和对应的评分规则
    """
    try:
        # 1. 如果有关键词，需要找到所有匹配的维度ID（包括维度本身匹配或其规则匹配的维度）
        if keyword:
            # 查找维度名称或描述匹配关键词的维度ID
            dimension_matched_ids = db.query(ScoreDimensions.id).filter(
                or_(
                    ScoreDimensions.dimension_name.contains(keyword),
                    ScoreDimensions.dimension_desc.contains(keyword)
                )
            ).all()
            dimension_matched_ids = [id[0] for id in dimension_matched_ids]
            
            # 查找规则描述或评判标准匹配关键词的维度ID
            rule_matched_dimension_ids = db.query(DimensionScoreRules.dimension_id).filter(
                or_(
                    DimensionScoreRules.level_desc.contains(keyword),
                    DimensionScoreRules.judge_criteria.contains(keyword)
                )
            ).distinct().all()
            rule_matched_dimension_ids = [id[0] for id in rule_matched_dimension_ids]
            
            # 合并所有匹配的维度ID
            all_matched_dimension_ids = list(set(dimension_matched_ids + rule_matched_dimension_ids))
            
            if not all_matched_dimension_ids:
                # 如果没有匹配的维度，返回空结果
                return {
                    "code": 200,
                    "msg": "查询成功",
                    "data": {
                        "dimensions_with_rules": [],
                        "pagination": {
                            "current_page": page,
                            "page_size": size,
                            "total_dimensions": 0,
                            "total_pages": 0
                        },
                        "summary": {
                            "total_dimensions": 0,
                            "total_rules": 0
                        }
                    }
                }
            
            # 构建维度查询条件，只查询匹配的维度
            dimensions_query = db.query(ScoreDimensions).filter(ScoreDimensions.id.in_(all_matched_dimension_ids))
        else:
            # 没有关键词时查询所有维度
            dimensions_query = db.query(ScoreDimensions)
        
        # 2. 获取维度总数
        total_dimensions = dimensions_query.count()
        
        # 3. 分页查询维度信息
        dimensions = dimensions_query.order_by(ScoreDimensions.id.asc()).offset((page - 1) * size).limit(size).all()
        
        # 4. 为每个维度查询对应的评分规则
        dimensions_with_rules = []
        total_rules_count = 0
        
        for dimension in dimensions:
            # 构建该维度的评分规则查询条件
            rules_query = db.query(DimensionScoreRules).filter(DimensionScoreRules.dimension_id == dimension.id)
            
            # 查询该维度的所有评分规则（不再在规则级别过滤关键词，因为维度已经是基于关键词筛选的）
            rules = rules_query.order_by(DimensionScoreRules.score_level.asc()).all()
            total_rules_count += len(rules)
            
            # 组装规则数据
            dimension_rules = [
                {
                    "id": rule.id,
                    "dimension_id": rule.dimension_id,
                    "score_level": rule.score_level,
                    "level_desc": rule.level_desc,
                    "judge_criteria": rule.judge_criteria,
                    "create_time": rule.create_time.strftime("%Y-%m-%d %H:%M:%S") if rule.create_time else None
                } for rule in rules
            ]
            
            dimensions_with_rules.append({
                "dimension_info": {
                    "id": dimension.id,
                    "dimension_name": dimension.dimension_name,
                    "description": dimension.dimension_desc,
                    "weight": float(dimension.dimension_weight),
                    "create_time": dimension.create_time.strftime("%Y-%m-%d %H:%M:%S") if dimension.create_time else None
                },
                "rules": dimension_rules,
                "rules_count": len(dimension_rules)
            })
        
        # 5. 构建响应数据
        response_data = {
            "dimensions_with_rules": dimensions_with_rules,
            "pagination": {
                "current_page": page,
                "page_size": size,
                "total_dimensions": total_dimensions,
                "total_pages": (total_dimensions + size - 1) // size
            },
            "summary": {
                "total_dimensions": total_dimensions,
                "current_page_dimensions": len(dimensions),
                "total_rules": total_rules_count
            }
        }
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": response_data
        }
        
    except Exception as e:
        return {
            "code": 500,
            "msg": f"查询失败: {str(e)}",
        }


@router.get("/rules/{rule_id}", summary="获取评分规则详情")
async def get_dimension_score_rule(
    rule_id: int,
    db: Session = Depends(get_db)
):
    """
    根据ID获取维度评分规则详情
    
    Args:
        rule_id: 规则ID
        db: 数据库会话
    
    Returns:
        统一格式的API响应，包含规则详情
    """
    try:
        rule = db.query(DimensionScoreRules).filter(DimensionScoreRules.id == rule_id).first()
        if not rule:
            return {
                "code": 404,
                "msg": f"规则ID {rule_id} 不存在",
            }
        
        # 获取关联的维度信息
        dimension = db.query(ScoreDimensions).filter(ScoreDimensions.id == rule.dimension_id).first()
        
        rule_data = {
            "id": rule.id,
            "dimension_id": rule.dimension_id,
            "score_level": rule.score_level,
            "level_desc": rule.level_desc,
            "judge_criteria": rule.judge_criteria,
            "create_time": rule.create_time.strftime("%Y-%m-%d %H:%M:%S") if rule.create_time else None,
            "dimension_info": {
                "dimension_name": dimension.dimension_name if dimension else None,
                "description": dimension.dimension_desc if dimension else None,
                "create_time": dimension.create_time.strftime("%Y-%m-%d %H:%M:%S") if dimension and dimension.create_time else None
            }
        }
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": rule_data
        }
        
    except Exception as e:
        return {
            "code": 500,
            "msg": f"查询失败: {str(e)}",
        }


@router.put("/rules/{rule_id}", summary="更新评分规则")
async def update_dimension_score_rule(
    rule_id: int,
    rule_update: DimensionScoreRuleUpdate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    更新维度评分规则
    
    Args:
        rule_id: 规则ID
        rule_update: 更新数据
        db: 数据库会话
        current_user: 当前用户
    
    Returns:
        统一格式的API响应，包含更新后的规则信息
    """
    try:
        # 查找要更新的规则
        db_rule = db.query(DimensionScoreRules).filter(DimensionScoreRules.id == rule_id).first()
        if not db_rule:
            return {
                "code": 404,
                "msg": f"规则ID {rule_id} 不存在",
            }
        
        # 检查维度是否存在（如果要更新维度ID）
        if rule_update.dimension_id is not None:
            dimension = db.query(ScoreDimensions).filter(ScoreDimensions.id == rule_update.dimension_id).first()
            if not dimension:
                return {
                    "code": 404,
                    "msg": f"维度ID {rule_update.dimension_id} 不存在",
                }
        
        # 检查唯一性约束（如果要更新维度ID或评分等级）
        if rule_update.dimension_id is not None or rule_update.score_level is not None:
            new_dimension_id = rule_update.dimension_id if rule_update.dimension_id is not None else db_rule.dimension_id
            new_score_level = rule_update.score_level if rule_update.score_level is not None else db_rule.score_level
            
            existing_rule = db.query(DimensionScoreRules).filter(
                and_(
                    DimensionScoreRules.dimension_id == new_dimension_id,
                    DimensionScoreRules.score_level == new_score_level,
                    DimensionScoreRules.id != rule_id
                )
            ).first()
            
            if existing_rule:
                return {
                    "code": 400,
                    "msg": f"维度ID {new_dimension_id} 的 {new_score_level} 分等级规则已存在"
                }
        
        # 更新规则
        update_data = rule_update.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_rule, field, value)
        
        db.commit()
        db.refresh(db_rule)
        
        return {
            "code": 200,
            "msg": "更新评分规则成功",
            "data": {
                "id": db_rule.id,
                "dimension_id": db_rule.dimension_id,
                "score_level": db_rule.score_level,
                "level_desc": db_rule.level_desc,
                "judge_criteria": db_rule.judge_criteria,
                "create_time": db_rule.create_time.strftime("%Y-%m-%d %H:%M:%S") if db_rule.create_time else None
            }
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"更新评分规则失败: {str(e)}"
        }


@router.delete("/rules/{rule_id}", summary="删除评分规则")
async def delete_dimension_score_rule(
    rule_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    删除维度评分规则
    
    Args:
        rule_id: 规则ID
        db: 数据库会话
        current_user: 当前用户
    
    Returns:
        统一格式的API响应
    """
    try:
        db_rule = db.query(DimensionScoreRules).filter(DimensionScoreRules.id == rule_id).first()
        if not db_rule:
            return {
                "code": 404,
                "msg": f"规则ID {rule_id} 不存在",
            }
        
        db.delete(db_rule)
        db.commit()
        
        return {
            "code": 200,
            "msg": f"规则ID {rule_id} 删除成功",
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"删除评分规则失败: {str(e)}",
        }


@router.delete("/{dimension_id}/rules", summary="删除维度的所有评分规则")
async def delete_dimension_rules(
    dimension_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    删除指定维度的所有评分规则
    
    Args:
        dimension_id: 维度ID
        db: 数据库会话
        current_user: 当前用户
    
    Returns:
        统一格式的API响应
    """
    try:
        # 检查维度是否存在
        dimension = db.query(ScoreDimensions).filter(ScoreDimensions.id == dimension_id).first()
        if not dimension:
            return {
                "code": 404,
                "msg": f"维度ID {dimension_id} 不存在",
            }
        
        # 删除该维度的所有规则
        deleted_count = db.query(DimensionScoreRules).filter(
            DimensionScoreRules.dimension_id == dimension_id
        ).delete()
        
        db.commit()
        
        return {
            "code": 200,
            "msg": f"已删除维度ID {dimension_id} 的 {deleted_count} 条规则",
            "data": {
                "dimension_id": dimension_id,
                "deleted_count": deleted_count
            }
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"删除维度规则失败: {str(e)}",
        }
